package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author：shaodan.wang
 * @date: 2022-04-19
 */


@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {


    //唯一约束异常处理
    @ExceptionHandler({SQLIntegrityConstraintViolationException.class})
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException e){
        if (e.getMessage().contains("Duplicate entry")){
            log.error(e.getMessage());
            return R.error("用户名已存在！");
        }else {

            return R.error("添加失败，未知异常");
        }
    }

    //关联菜品异常
    @ExceptionHandler({CustomException.class})
    public R<String> CustomExceptionHandler(CustomException e) {

        return R.error(e.getMessage());
    }


}
